package com.sxj.PDMS.controller.admin;

import cn.hutool.core.io.FileUtil;
import com.sxj.PDMS.common.BaseResponse;
import com.sxj.PDMS.common.ErrorCode;
import com.sxj.PDMS.common.Result;
import com.sxj.PDMS.exception.BusinessException;
import com.sxj.PDMS.exception.ThrowUtils;
import com.sxj.PDMS.model.dto.admin.*;
import com.sxj.PDMS.model.dto.student.YusRecordRequest;
import com.sxj.PDMS.model.entity.*;
import com.sxj.PDMS.model.vo.*;
import com.sxj.PDMS.service.ActivistApplicationInformationListService;
import com.sxj.PDMS.service.DevelopTheObjectApplicationInformationListService;
import com.sxj.PDMS.service.FullPartyMemberInformationListService;
import com.sxj.PDMS.service.ListOfProbationaryPartyApplicationInformationService;
import com.sxj.PDMS.utils.ExcelUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;


@RestController
@RequestMapping("/admin")
@Slf4j
public class MemberController {

    @Autowired
    private ActivistApplicationInformationListService activistApplicationInformationListService;
    @Autowired
    private DevelopTheObjectApplicationInformationListService developTheObjectApplicationInformationListService;
    @Autowired
    private ListOfProbationaryPartyApplicationInformationService listOfProbationaryPartyApplicationInformationService;
    @Autowired
    private FullPartyMemberInformationListService fullPartyMemberInformationListService;

    @PostMapping("/register_activistApplication")
    public BaseResponse registerActivistApplications(@RequestPart("file") MultipartFile multipartFile,
                                         HttpServletRequest request) {

        // 校验文件
        long size = multipartFile.getSize();
        String originalFilename = multipartFile.getOriginalFilename();
        // 校验文件大小
        final long ONE_MB = 10 * 1024 * 1024L;
        ThrowUtils.throwIf(size > ONE_MB, ErrorCode.PARAMS_ERROR, "文件超过 10M");

        String suffix = FileUtil.getSuffix(originalFilename);
        final List<String> validFileSuffixList = Arrays.asList("xlsx");
        ThrowUtils.throwIf(!validFileSuffixList.contains(suffix), ErrorCode.PARAMS_ERROR, "文件后缀非法");

        // 读取学生信息
        List<ActivistApplicationInformationList> list = ExcelUtils.excelToActivistApplicationList(multipartFile);

        // 批量注册学生账号
        activistApplicationInformationListService.registerActivistApplicationBatch(list);

        // 返回成功信息
        return Result.success();
    }

    @PostMapping("/register_developTheObjectApplication")
    public BaseResponse registerDevelopTheObjectApplications(@RequestPart("file") MultipartFile multipartFile,
                                                     HttpServletRequest request) {

        // 校验文件
        long size = multipartFile.getSize();
        String originalFilename = multipartFile.getOriginalFilename();
        // 校验文件大小
        final long ONE_MB = 10 * 1024 * 1024L;
        ThrowUtils.throwIf(size > ONE_MB, ErrorCode.PARAMS_ERROR, "文件超过 10M");
        // 校验文件后缀 aaa.png
        String suffix = FileUtil.getSuffix(originalFilename);
        final List<String> validFileSuffixList = Arrays.asList("xlsx");
        ThrowUtils.throwIf(!validFileSuffixList.contains(suffix), ErrorCode.PARAMS_ERROR, "文件后缀非法");

        // 读取学生信息
        List<DevelopTheObjectApplicationInformationList> list = ExcelUtils.excelToDevelopTheObjectApplicationList(multipartFile);

        // 批量注册学生账号
        developTheObjectApplicationInformationListService.registerDevelopTheObjectApplicationBatch(list);

        // 返回成功信息
        return Result.success();
    }

    @PostMapping("/register_probationaryPartyApplication")
    public BaseResponse registerProbationaryPartyApplications(@RequestPart("file") MultipartFile multipartFile,
                                                     HttpServletRequest request) {

        // 校验文件
        long size = multipartFile.getSize();
        String originalFilename = multipartFile.getOriginalFilename();
        // 校验文件大小
        final long ONE_MB = 10 * 1024 * 1024L;
        ThrowUtils.throwIf(size > ONE_MB, ErrorCode.PARAMS_ERROR, "文件超过 10M");
        // 校验文件后缀 aaa.png
        String suffix = FileUtil.getSuffix(originalFilename);
        final List<String> validFileSuffixList = Arrays.asList("xlsx");
        ThrowUtils.throwIf(!validFileSuffixList.contains(suffix), ErrorCode.PARAMS_ERROR, "文件后缀非法");

        // 读取学生信息
        List<ListOfProbationaryPartyApplicationInformation> list = ExcelUtils.excelToProbationaryPartyApplicationList(multipartFile);

        // 批量注册学生账号
        listOfProbationaryPartyApplicationInformationService.registerProbationaryPartyApplicationBatch(list);

        // 返回成功信息
        return Result.success();
    }

    @PostMapping("/register_fullPartyApplication")
    public BaseResponse registerFullPartyApplications(@RequestPart("file") MultipartFile multipartFile,
                                                              HttpServletRequest request) {

        // 校验文件
        long size = multipartFile.getSize();
        String originalFilename = multipartFile.getOriginalFilename();
        // 校验文件大小
        final long ONE_MB = 10 * 1024 * 1024L;
        ThrowUtils.throwIf(size > ONE_MB, ErrorCode.PARAMS_ERROR, "文件超过 10M");
        // 校验文件后缀 aaa.png
        String suffix = FileUtil.getSuffix(originalFilename);
        final List<String> validFileSuffixList = Arrays.asList("xlsx");
        ThrowUtils.throwIf(!validFileSuffixList.contains(suffix), ErrorCode.PARAMS_ERROR, "文件后缀非法");

        // 读取学生信息
        List<FullPartyMemberInformationList> list = ExcelUtils.excelToFullPartyApplicationList(multipartFile);

        // 批量注册学生账号
        fullPartyMemberInformationListService.registerFullPartyApplicationBatch(list);

        // 返回成功信息
        return Result.success();
    }

    @GetMapping("/selectAll_activistApplicationInformationList")
    public BaseResponse<PagingQueryResponse<ActivistApplicationInformationListVO>> selectActivistApplication(@RequestParam(defaultValue = "1") Integer page,
                                                                                                             @RequestParam(defaultValue = "10") Integer pageSize) {
        log.info("分页查询 ：page:{}, pageSize:{}", page, pageSize);
        PagingQueryResponse<ActivistApplicationInformationListVO> pagingQueryResponse = activistApplicationInformationListService.selectAll(page, pageSize);
        return Result.success(pagingQueryResponse);

    }
    @GetMapping("/select_activistApplicationInformationList")
    public BaseResponse<PagingQueryResponse<ActivistApplicationInformationListVO>> selectActivistApplicationWithCondition(@RequestParam(defaultValue = "1") Integer page,
                                                                                      @RequestParam(defaultValue = "10") Integer pageSize,
                                                                                      String studentNumber,String name) {

        PagingQueryResponse<ActivistApplicationInformationListVO> pagingQueryResponse = activistApplicationInformationListService.activistApplicationInformationList(page,pageSize,studentNumber,name);

        return Result.success(pagingQueryResponse);
    }

    @GetMapping("/selectAll_developTheObjectApplicationInformationList")
    public BaseResponse<PagingQueryResponse<DevelopTheObjectApplicationInformationListVO>> selectDevelopApplication(@RequestParam(defaultValue = "1") Integer page,

                                                                                                                      @RequestParam(defaultValue = "10") Integer pageSize) {
        log.info("分页查询 ：page:{}, pageSize:{}", page, pageSize);
        PagingQueryResponse<DevelopTheObjectApplicationInformationListVO> pagingQueryResponse = developTheObjectApplicationInformationListService.selectAll(page, pageSize);

        return Result.success(pagingQueryResponse);
    }
    @GetMapping("/select_developTheObjectApplicationInformationList")
    public BaseResponse<PagingQueryResponse<DevelopTheObjectApplicationInformationListVO>> selectDevelopApplicationWithCondition(@RequestParam(defaultValue = "1") Integer page,
                                                                                                                                 @RequestParam(defaultValue = "10") Integer pageSize,
                                                                                                                                 String studentNumber, String name) {

        PagingQueryResponse<DevelopTheObjectApplicationInformationListVO> pagingQueryResponse = developTheObjectApplicationInformationListService.developTheObjectApplicationInformationList(page,pageSize,studentNumber,name);

        return Result.success(pagingQueryResponse);
    }

    @GetMapping("/selectAll_listOfProbationaryPartyApplicationInformation")
    public BaseResponse<PagingQueryResponse<ListOfProbationaryPartyApplicationInformationVO>> selectProbationaryPartyApplication(@RequestParam(defaultValue = "1") Integer page,

                                                                                                                                 @RequestParam(defaultValue = "10") Integer pageSize) {
        log.info("分页查询 ：page:{}, pageSize:{}", page, pageSize);
        PagingQueryResponse<ListOfProbationaryPartyApplicationInformationVO> pagingQueryResponse = listOfProbationaryPartyApplicationInformationService.selectAll(page, pageSize);
        return Result.success(pagingQueryResponse);
    }
    @GetMapping("/select_listOfProbationaryPartyApplicationInformation")
    public BaseResponse<PagingQueryResponse<ListOfProbationaryPartyApplicationInformationVO>> selectProbationaryPartyApplicationWithCondition(@RequestParam(defaultValue = "1") Integer page,
                                                                                                                                              @RequestParam(defaultValue = "10") Integer pageSize,
                                                                                                                                              String studentNumber, String name) {

        PagingQueryResponse<ListOfProbationaryPartyApplicationInformationVO> pagingQueryResponse = listOfProbationaryPartyApplicationInformationService.listOfProbationaryPartyApplicationInformation(page,pageSize,studentNumber,name);
        return Result.success(pagingQueryResponse);
    }

    @GetMapping("/selectAll_fullPartyMemberInformationList")
    public BaseResponse<PagingQueryResponse<FullPartyMemberInformationListVO>> selectFullPartyApplication(@RequestParam(defaultValue = "1") Integer page,
                                                                                                        @RequestParam(defaultValue = "10") Integer pageSize) {
        log.info("分页查询 ：page:{}, pageSize:{}", page, pageSize);
        PagingQueryResponse<FullPartyMemberInformationListVO> pagingQueryResponse = fullPartyMemberInformationListService.selectAll(page, pageSize);
        return Result.success(pagingQueryResponse);
    }
    @GetMapping("/select_fullPartyMemberInformationList")
    public BaseResponse<PagingQueryResponse<FullPartyMemberInformationListVO>> selectFullPartyApplicationWithCondition(@RequestParam(defaultValue = "1") Integer page,
                                                                                                                       @RequestParam(defaultValue = "10") Integer pageSize,
                                                                                                                       String studentNumber, String name) {

        PagingQueryResponse<FullPartyMemberInformationListVO> pagingQueryResponse = fullPartyMemberInformationListService.fullPartyMemberInformationList(page,pageSize,studentNumber,name);
        return Result.success(pagingQueryResponse);
    }

    /**
     * 根据条件查询并下载积极分子的学生信息
     *
     * @param studentNumber
     * @param name
     * @return response
     */
    // todo 前后端联调 swagger无法测试
    @ApiOperation(value = "selectAndDownloadActivist",produces = "application/octet-stream")
    @GetMapping("/selectAndDownload_activist")
    public void selectAndDownloadActivist( String studentNumber, String name,
                                          HttpServletResponse response) {
        log.info("根据条件查询并下载积极分子信息 ：studentNumber:{},name:{}", studentNumber,name);

        try {
            // 设置响应内容类型
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

            // 设置响应头，告诉浏览器这是一个附件，应该下载而不是直接打开
            String fileName = "积极分子基本信息表.xlsx"; // 你可以根据需要自定义文件名
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

            // 调用服务层方法，并传递响应对象
            activistApplicationInformationListService.selectAllStudentAndDownload(studentNumber,name, response);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "下载积极分子基本信息失败");
        }
    }

    /**
     * 根据条件查询并下载发展对象的学生信息
     *
     * @param studentNumber
     * @param name
     * @return response
     */
    // todo 前后端联调 swagger无法测试
    @ApiOperation(value = "selectAndDownloadDevelop",produces = "application/octet-stream")
    @GetMapping("/selectAndDownload_develop")
    public void selectAndDownloadDevelop( String studentNumber, String name,
                                           HttpServletResponse response) {
        log.info("根据条件查询并下载发展对象信息 ：studentNumber:{},name:{}", studentNumber,name);

        try {
            // 设置响应内容类型
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

            // 设置响应头，告诉浏览器这是一个附件，应该下载而不是直接打开
            String fileName = "发展对象基本信息表.xlsx"; // 你可以根据需要自定义文件名
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

            // 调用服务层方法，并传递响应对象
            developTheObjectApplicationInformationListService.selectAllStudentAndDownload(studentNumber,name, response);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "下载发展对象基本信息失败");
        }
    }

    /**
     * 根据条件查询并下载预备党员的学生信息
     *
     * @param studentNumber
     * @param name
     * @return response
     */
    // todo 前后端联调 swagger无法测试
    @ApiOperation(value = "selectAndDownloadProbationary",produces = "application/octet-stream")
    @GetMapping("/selectAndDownload_probationary")
    public void selectAndDownloadProbationary( String studentNumber, String name,
                                           HttpServletResponse response) {
        log.info("根据条件查询并下载预备党员信息 ：studentNumber:{},name:{}", studentNumber,name);

        try {
            // 设置响应内容类型
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

            // 设置响应头，告诉浏览器这是一个附件，应该下载而不是直接打开
            String fileName = "预备党员基本信息表.xlsx"; // 你可以根据需要自定义文件名
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

            // 调用服务层方法，并传递响应对象
            listOfProbationaryPartyApplicationInformationService.selectAllStudentAndDownload(studentNumber,name, response);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "下载预备党员基本信息失败");
        }
    }

    /**
     * 根据条件查询并下载正式党员的学生信息
     *
     * @param studentNumber
     * @param name
     * @return response
     */
    // todo 前后端联调 swagger无法测试
    @ApiOperation(value = "selectAndDownloadFormal",produces = "application/octet-stream")
    @GetMapping("/selectAndDownload_formal")
    public void selectAndDownloadFormal( String studentNumber, String name,
                                           HttpServletResponse response) {
        log.info("根据条件查询并下载正式党员信息 ：studentNumber:{},name:{}", studentNumber,name);

        try {
            // 设置响应内容类型
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

            // 设置响应头，告诉浏览器这是一个附件，应该下载而不是直接打开
            String fileName = "正式党员基本信息表.xlsx"; // 你可以根据需要自定义文件名
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

            // 调用服务层方法，并传递响应对象
            fullPartyMemberInformationListService.selectAllStudentAndDownload(studentNumber,name, response);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "下载正式党员基本信息失败");
        }
    }
}
